using System.Windows.Forms;
using TeachingManagementSystem.BLL;
using TeachingManagementSystem.Models;

namespace TeachingManagementSystem.Forms.CourseManagement
{
    public partial class CourseEditForm : Form
    {
        private CourseBLL _courseBLL;
        private UserBLL _userBLL;
        private Course _course;
        private bool _isEditMode;

        public CourseEditForm(Course course)
        {
            InitializeComponent();
            _courseBLL = new CourseBLL();
            _userBLL = new UserBLL();
            _course = course;
            _isEditMode = course != null;
            InitializeForm();
            // 设置为适当的窗口大小
            this.WindowState = FormWindowState.Normal;
            this.Size = new System.Drawing.Size(700, 550);  // 增大窗口
            this.FormBorderStyle = FormBorderStyle.FixedSingle;
            this.StartPosition = FormStartPosition.CenterScreen;
        }

        private void InitializeForm()
        {
            // 初始化状态下拉框
            comboBoxStatus.DataSource = Enum.GetValues(typeof(CourseStatus));

            // 加载教师列表（只显示教师角色的用户）
            LoadTeachers();

            // 初始化系部下拉框
            try
            {
                var departments = _courseBLL.GetAllDepartments();
                foreach (var department in departments)
                {
                    comboBoxDepartment.Items.Add(department);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"加载系部列表时出错: {ex.Message}");
                // 备用系部选项
                comboBoxDepartment.Items.AddRange(new string[] {
                    "计算机系", "数学系", "外语系", "中文系", "物理系", "化学系"
                });
            }

            if (_isEditMode)
            {
                // 编辑模式，填充表单
                this.Text = "编辑课程";
                if (_course != null)
                {
                    txtCourseID.Text = _course.CourseID.ToString();
                    txtCourseCode.Text = _course.CourseCode ?? string.Empty;
                    txtCourseName.Text = _course.CourseName ?? string.Empty;
                    txtDescription.Text = _course.Description ?? string.Empty;
                    txtCredit.Text = _course.Credit.ToString();
                    txtTotalHours.Text = _course.TotalHours.ToString();
                    comboBoxDepartment.SelectedItem = _course.Department ?? string.Empty;
                    // 选择对应的教师
                    foreach (var item in comboBoxTeacher.Items)
                    {
                        if (item != null && item.ToString().Contains(_course.TeacherID.ToString()))
                        {
                            comboBoxTeacher.SelectedItem = item;
                            break;
                        }
                    }
                    comboBoxStatus.SelectedItem = _course.Status;
                }
                btnSave.Text = "更新";
            }
            else
            {
                // 添加模式
                this.Text = "添加课程";
                txtCourseID.Text = "自动生成";
                txtCourseID.ReadOnly = true;
                comboBoxStatus.SelectedItem = CourseStatus.NotStarted;
            }
        }

        private void LoadTeachers()
        {
            var teachers = _userBLL.GetUsersByRole(UserRole.Teacher);
            foreach (var teacher in teachers)
            {
                comboBoxTeacher.Items.Add($"{teacher.FullName} (ID:{teacher.UserID})");
            }
        }

        private int GetSelectedTeacherID()
        {
            if (comboBoxTeacher.SelectedItem != null)
            {
                string selectedText = comboBoxTeacher.SelectedItem?.ToString() ?? string.Empty;
                int startIndex = selectedText.IndexOf("ID:") + 3;
                int endIndex = selectedText.IndexOf(")", startIndex);
                if (startIndex > 0 && endIndex > startIndex)
                {
                    string idText = selectedText.Substring(startIndex, endIndex - startIndex);
                    if (int.TryParse(idText, out int teacherID))
                    {
                        return teacherID;
                    }
                }
            }
            return 0;
        }

        private void InitializeComponent()
        {
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.label3 = new System.Windows.Forms.Label();
            this.label4 = new System.Windows.Forms.Label();
            this.label5 = new System.Windows.Forms.Label();
            this.label6 = new System.Windows.Forms.Label();
            this.label7 = new System.Windows.Forms.Label();
            this.label8 = new System.Windows.Forms.Label();
            this.txtCourseID = new System.Windows.Forms.TextBox();
            this.txtCourseCode = new System.Windows.Forms.TextBox();
            this.txtCourseName = new System.Windows.Forms.TextBox();
            this.txtDescription = new System.Windows.Forms.TextBox();
            this.txtCredit = new System.Windows.Forms.TextBox();
            this.txtTotalHours = new System.Windows.Forms.TextBox();
            this.comboBoxDepartment = new System.Windows.Forms.ComboBox();
            this.comboBoxTeacher = new System.Windows.Forms.ComboBox();
            this.comboBoxStatus = new System.Windows.Forms.ComboBox();
            this.btnSave = new System.Windows.Forms.Button();
            this.btnCancel = new System.Windows.Forms.Button();
            this.SuspendLayout();
            // 
            // label1
            // 
            this.label1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)));
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(40, 20);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(52, 15);
            this.label1.TabIndex = 0;
            this.label1.Text = "课程ID";
            // 
            // label2
            // 
            this.label2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)));
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(40, 55);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(52, 15);
            this.label2.TabIndex = 1;
            this.label2.Text = "课程代码";
            // 
            // label3
            // 
            this.label3.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)));
            this.label3.AutoSize = true;
            this.label3.Location = new System.Drawing.Point(40, 90);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(52, 15);
            this.label3.TabIndex = 2;
            this.label3.Text = "课程名称";
            // 
            // label4
            // 
            this.label4.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)));
            this.label4.AutoSize = true;
            this.label4.Location = new System.Drawing.Point(40, 125);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(52, 15);
            this.label4.TabIndex = 3;
            this.label4.Text = "课程描述";
            // 
            // label5
            // 
            this.label5.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)));
            this.label5.AutoSize = true;
            this.label5.Location = new System.Drawing.Point(40, 200);
            this.label5.Name = "label5";
            this.label5.Size = new System.Drawing.Size(52, 15);
            this.label5.TabIndex = 4;
            this.label5.Text = "学分";
            // 
            // label6
            // 
            this.label6.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)));
            this.label6.AutoSize = true;
            this.label6.Location = new System.Drawing.Point(40, 235);
            this.label6.Name = "label6";
            this.label6.Size = new System.Drawing.Size(52, 15);
            this.label6.TabIndex = 5;
            this.label6.Text = "总课时";
            // 
            // label7
            // 
            this.label7.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)));
            this.label7.AutoSize = true;
            this.label7.Location = new System.Drawing.Point(40, 270);
            this.label7.Name = "label7";
            this.label7.Size = new System.Drawing.Size(52, 15);
            this.label7.TabIndex = 6;
            this.label7.Text = "所属系部";
            // 
            // label8
            // 
            this.label8.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)));
            this.label8.AutoSize = true;
            this.label8.Location = new System.Drawing.Point(40, 305);
            this.label8.Name = "label8";
            this.label8.Size = new System.Drawing.Size(52, 15);
            this.label8.TabIndex = 7;
            this.label8.Text = "授课教师";
            // 
            // txtCourseID
            // 
            this.txtCourseID.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)));
            this.txtCourseID.Location = new System.Drawing.Point(120, 15);
            this.txtCourseID.Name = "txtCourseID";
            this.txtCourseID.Size = new System.Drawing.Size(200, 25);
            this.txtCourseID.TabIndex = 8;
            this.txtCourseID.ReadOnly = true;
            // 
            // txtCourseCode
            // 
            this.txtCourseCode.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)));
            this.txtCourseCode.Location = new System.Drawing.Point(120, 50);
            this.txtCourseCode.Name = "txtCourseCode";
            this.txtCourseCode.Size = new System.Drawing.Size(200, 25);
            this.txtCourseCode.TabIndex = 9;
            // 
            // txtCourseName
            // 
            this.txtCourseName.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)));
            this.txtCourseName.Location = new System.Drawing.Point(120, 85);
            this.txtCourseName.Name = "txtCourseName";
            this.txtCourseName.Size = new System.Drawing.Size(200, 25);
            this.txtCourseName.TabIndex = 10;
            // 
            // txtDescription
            // 
            this.txtDescription.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)));
            this.txtDescription.Location = new System.Drawing.Point(120, 120);
            this.txtDescription.Multiline = true;
            this.txtDescription.Name = "txtDescription";
            this.txtDescription.Size = new System.Drawing.Size(200, 70);
            this.txtDescription.TabIndex = 11;
            // 
            // txtCredit
            // 
            this.txtCredit.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)));
            this.txtCredit.Location = new System.Drawing.Point(120, 195);
            this.txtCredit.Name = "txtCredit";
            this.txtCredit.Size = new System.Drawing.Size(200, 25);
            this.txtCredit.TabIndex = 12;
            // 
            // txtTotalHours
            // 
            this.txtTotalHours.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)));
            this.txtTotalHours.Location = new System.Drawing.Point(120, 230);
            this.txtTotalHours.Name = "txtTotalHours";
            this.txtTotalHours.Size = new System.Drawing.Size(200, 25);
            this.txtTotalHours.TabIndex = 13;
            // 
            // comboBoxDepartment
            // 
            this.comboBoxDepartment.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)));
            this.comboBoxDepartment.FormattingEnabled = true;
            this.comboBoxDepartment.Location = new System.Drawing.Point(120, 265);
            this.comboBoxDepartment.Name = "comboBoxDepartment";
            this.comboBoxDepartment.Size = new System.Drawing.Size(200, 23);
            this.comboBoxDepartment.TabIndex = 14;
            // 
            // comboBoxTeacher
            // 
            this.comboBoxTeacher.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)));
            this.comboBoxTeacher.FormattingEnabled = true;
            this.comboBoxTeacher.Location = new System.Drawing.Point(120, 300);
            this.comboBoxTeacher.Name = "comboBoxTeacher";
            this.comboBoxTeacher.Size = new System.Drawing.Size(200, 23);
            this.comboBoxTeacher.TabIndex = 15;
            // 
            // comboBoxStatus
            // 
            this.comboBoxStatus.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)));
            this.comboBoxStatus.FormattingEnabled = true;
            this.comboBoxStatus.Location = new System.Drawing.Point(120, 335);
            this.comboBoxStatus.Name = "comboBoxStatus";
            this.comboBoxStatus.Size = new System.Drawing.Size(200, 23);
            this.comboBoxStatus.TabIndex = 16;
            // 
            // btnSave
            // 
            this.btnSave.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
            this.btnSave.Location = new System.Drawing.Point(500, 480);
            this.btnSave.Name = "btnSave";
            this.btnSave.Size = new System.Drawing.Size(90, 35);
            this.btnSave.TabIndex = 17;
            this.btnSave.Text = "保存";
            this.btnSave.UseVisualStyleBackColor = true;
            this.btnSave.Click += new System.EventHandler(this.btnSave_Click);
            // 
            // btnCancel
            // 
            this.btnCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
            this.btnCancel.Location = new System.Drawing.Point(400, 480);
            this.btnCancel.Name = "btnCancel";
            this.btnCancel.Size = new System.Drawing.Size(90, 35);
            this.btnCancel.TabIndex = 18;
            this.btnCancel.Text = "取消";
            this.btnCancel.UseVisualStyleBackColor = true;
            this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
            // 
            // CourseEditForm
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 15F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(700, 550);
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.Controls.Add(this.btnCancel);
            this.Controls.Add(this.btnSave);
            this.Controls.Add(this.comboBoxStatus);
            this.Controls.Add(this.comboBoxTeacher);
            this.Controls.Add(this.comboBoxDepartment);
            this.Controls.Add(this.txtTotalHours);
            this.Controls.Add(this.txtCredit);
            this.Controls.Add(this.txtDescription);
            this.Controls.Add(this.txtCourseName);
            this.Controls.Add(this.txtCourseCode);
            this.Controls.Add(this.txtCourseID);
            this.Controls.Add(this.label8);
            this.Controls.Add(this.label7);
            this.Controls.Add(this.label6);
            this.Controls.Add(this.label5);
            this.Controls.Add(this.label4);
            this.Controls.Add(this.label3);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.label1);
            this.Name = "CourseEditForm";
            this.Text = "课程信息";
            this.ResumeLayout(false);
            this.PerformLayout();
        }

        private void btnSave_Click(object? sender, EventArgs e)
        {
            // 验证输入
            if (string.IsNullOrEmpty(txtCourseCode.Text.Trim()))
            {
                MessageBox.Show("课程代码不能为空", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtCourseCode.Focus();
                return;
            }

            if (string.IsNullOrEmpty(txtCourseName.Text.Trim()))
            {
                MessageBox.Show("课程名称不能为空", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtCourseName.Focus();
                return;
            }

            if (!int.TryParse(txtCredit.Text.Trim(), out int credit) || credit <= 0)
            {
                MessageBox.Show("请输入有效的学分", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtCredit.Focus();
                return;
            }

            if (!int.TryParse(txtTotalHours.Text.Trim(), out int totalHours) || totalHours <= 0)
            {
                MessageBox.Show("请输入有效的课时", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtTotalHours.Focus();
                return;
            }

            if (comboBoxDepartment.SelectedItem == null)
            {
                MessageBox.Show("请选择所属系部", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            int teacherID = GetSelectedTeacherID();
            if (teacherID == 0)
            {
                MessageBox.Show("请选择授课教师", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            try
            {
                if (_isEditMode)
                {
                    // 更新课程
                    _course.CourseCode = txtCourseCode.Text.Trim();
                    _course.CourseName = txtCourseName.Text.Trim();
                    _course.Description = txtDescription.Text.Trim();
                    _course.Credit = credit;
                    _course.TotalHours = totalHours;
                    _course.Department = comboBoxDepartment.SelectedItem?.ToString() ?? string.Empty;
                    _course.TeacherID = teacherID;
                    _course.Status = comboBoxStatus.SelectedItem != null ? (CourseStatus)comboBoxStatus.SelectedItem : CourseStatus.NotStarted;

                    _courseBLL.UpdateCourse(_course);
                    MessageBox.Show("课程信息已更新", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    // 添加新课程
                    Course newCourse = new Course
                    {
                        CourseCode = txtCourseCode.Text.Trim(),
                        CourseName = txtCourseName.Text.Trim(),
                        Description = txtDescription.Text.Trim(),
                        Credit = credit,
                        TotalHours = totalHours,
                        Department = comboBoxDepartment.SelectedItem?.ToString() ?? string.Empty,
                        TeacherID = teacherID,
                        Status = comboBoxStatus.SelectedItem != null ? (CourseStatus)comboBoxStatus.SelectedItem : CourseStatus.NotStarted
                    };

                    _courseBLL.AddCourse(newCourse);
                    MessageBox.Show("课程添加成功", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }

                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnCancel_Click(object? sender, EventArgs e)
        {
            this.Close();
        }

        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.Label label4;
        private System.Windows.Forms.Label label5;
        private System.Windows.Forms.Label label6;
        private System.Windows.Forms.Label label7;
        private System.Windows.Forms.Label label8;
        private System.Windows.Forms.TextBox txtCourseID;
        private System.Windows.Forms.TextBox txtCourseCode;
        private System.Windows.Forms.TextBox txtCourseName;
        private System.Windows.Forms.TextBox txtDescription;
        private System.Windows.Forms.TextBox txtCredit;
        private System.Windows.Forms.TextBox txtTotalHours;
        private System.Windows.Forms.ComboBox comboBoxDepartment;
        private System.Windows.Forms.ComboBox comboBoxTeacher;
        private System.Windows.Forms.ComboBox comboBoxStatus;
        private System.Windows.Forms.Button btnSave;
        private System.Windows.Forms.Button btnCancel;
    }
}